#!/bin/bash

CURRDIR=$(realpath $(dirname $0))
if [ -f "$CURRDIR/config.sh" ]; then
	source "$CURRDIR/config.sh"
else
	echo '== config.sh not found, exiting...'; exit 23
fi

echo '== Stopping running containers...'

stop_fails=0

while read container; do
	sudo docker stop "$container"
	sudo docker rm "$container"
	if [ "$?" = "0" ]; then
		echo "== Stopped container: $container"
		sed -i "/^${container}$/d" "${CURRDIR}/run/running_containers"
	else
		echo "== Could not stop container: $container"
		stop_fails=$((stop_fails+1))
	fi
done < "${CURRDIR}/run/running_containers"

# All containers removed, so remove the running_containers file
if [ "$stop_fails" -eq 0 ]; then
	rm "${CURRDIR}/run/running_containers"
fi

echo '== Stopping automatic tunneling url...'
if [ -f "${CURRDIR}/run/tunneling_pid" ]; then
	kill -9 `cat "${CURRDIR}/run/tunneling_pid"` && rm "${CURRDIR}/run/tunneling_pid" && rm "${CURRDIR}/run/tunneling_url"
else
	echo 'No record for local tunneling service found. Skipping...'
fi

echo '== Finished.'
